package com.musiklegal;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.musiklegal.MyD.Banding;
import com.musiklegal.MyD.MusicAdapter;
import com.musiklegal.MyD.MusicAdapter.ViewHolder;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MyPlayList extends Activity implements Runnable 
{

	final String []menu = {Settings.info,Settings.del,Settings.deal};
	List<SongD> hasil;
	List<SongD> cari;
	ListView list;
	Button search, prev,play,next/*,stop*/,repeat,shuffle;
	SeekBar timeBar;
	TextView timeText,status;
	int duration,elapse;
	SongD nextSong;
	WebView wv;
	boolean close,replayed, prepared,firstSong;
	MediaPlayer player;
	EditText srch;
	MusicAdapter ma;
	Banding banding;
	Thread t;
	Random  rand;
	Handler h;
	AlertDialog.Builder alert;
	Toast to;
	Timer time;
	TextView textv;
	ImageView iv;
	
	public void onResume()
    {
    	super.onResume();
    	
    	new Thread(new Runnable(){

			public void run() {
				if(MusikLegal.internet(getApplicationContext()))
				{
		    		if(MusikLegal.log!=null&&MusikLegal.log.listSong.size()>0)
		        	{
		        		try {
							MusikLegal.log.send();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		        	}
				}
				
			}}).start();
    /*
    	
    	}*/
    }
	
	private synchronized void init()
	{
		if(MyD.player==null)
			MyD.player = new MediaPlayer();
		player = MyD.player;
		setContentView(R.layout.myd);
		MainMenu.setStatus(this);
		hasil =MusikLegal.myPlaylist;
		
		duration=0;
		elapse=0;
		
		//MyD.paused=false;
		close=false;
		prepared=false;
		replayed=false;
		firstSong=true;
		rand = new Random();
		search = (Button) findViewById(R.id.srchdlbut);
		srch = (EditText) findViewById(R.id.srchdl);
		list = (ListView) findViewById(R.id.PhoneMusicList);
		prev = (Button) findViewById(R.id.prev);
		play = (Button) findViewById(R.id.play);
		next = (Button) findViewById(R.id.next);
		textv = (TextView) findViewById(R.id.judul);
		
		iv = (ImageView) findViewById(R.id.banner);
		
		new Thread(new Runnable(){

			public void run() {
				try {
					
					MyD.loadBanner(MyPlayList.this,iv,h);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (NullPointerException e)
				{
					e.printStackTrace();
				}
				
			}}).start();
			
		
		
		textv.setText("My PlayList");
		cari = new ArrayList<SongD>();
		repeat = (Button) findViewById(R.id.repeat);
		switch (MyD.modeRepeat) {
		case 0:
			repeat.setBackgroundResource(R.drawable.rpoff);
			break;
		case 1:
			repeat.setBackgroundResource(R.drawable.rpall);
			break;
		case 2:
			repeat.setBackgroundResource(R.drawable.rpone);
			break;
		}
		shuffle = (Button) findViewById(R.id.shuffle);
		if(MyD.shuffling)
			shuffle.setBackgroundResource(R.drawable.shon);
		else
			shuffle.setBackgroundResource(R.drawable.shoff);
		timeText = (TextView) findViewById(R.id.timeelapse);
		timeBar = (SeekBar) findViewById(R.id.timeBar);
		status = (TextView) findViewById(R.id.status);
		alert = new AlertDialog.Builder(this);
		h = new Handler();
		banding = new Banding();
		
		sortList();
		ma = new MusicAdapter(this,hasil);
		
		
		list.setAdapter(ma);
		
		list.setOnItemLongClickListener(new OnItemLongClickListener(){

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				
				alert.setTitle( Settings.joption );
				alert.setIcon(R.drawable.oc2);
	        	alert.setItems( menu , new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int item) {
	                	
	                	switch(item)
	                	{
	                		case 0:
	                			TrackInfo.item=(SongD) list.getItemAtPosition(arg2);
	                			TrackInfo.isCatalogue=true;
	                			TrackInfo.fromCatalogue=false;
	                			startActivity(new Intent(getApplicationContext(),TrackInfo.class));
	                		break;
	                		case 1:
	                			SongD it = (SongD) list.getItemAtPosition(arg2);
	                			if(MyD.currentSong!=null&&MyD.currentSong.equals(it))
	                			{
	                				stop();
	                				
	                				MyD.currentSong=null;
	                				MyD.isInited=false;
	                				MyD.paused=false;
	                			}
	                			removeItem(it);
	                			/**/
	                			Toast.makeText(getApplicationContext(), "Song Deleted", Toast.LENGTH_SHORT).show();
	                			list.invalidateViews();
	                			break;
	                		case 2:
	                			if(MyD.currentSong!=null&&hasil.contains(MyD.currentSong))
	                			{
	                				stop();
	                				MyD.currentSong=null;
	                				MyD.isInited=false;
	                				MyD.paused= false;
	                			}
	                				
	                			removeAll();
	                			Toast.makeText(getApplicationContext(), "All Songs in PlayList are deleted", Toast.LENGTH_SHORT).show();
	                			list.invalidateViews();
	                			
	                	
	                	}
	                	
	                
	                }});
	        	alert.setCancelable(true);
	        	alert.create();
	        	alert.show();
				
				return false;
				
			}});
		
		repeat.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				changeMode();
				switch(MyD.modeRepeat)
				{
				case 0: repeat.setBackgroundResource(R.drawable.rpoff);
				break;
				case 1: repeat.setBackgroundResource(R.drawable.rpall);
				break;
				case 2: repeat.setBackgroundResource(R.drawable.rpone);
				break;
				}
				
			}});
		
		shuffle.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				changeShuffle();
				
				if(MyD.shuffling)
					shuffle.setBackgroundResource(R.drawable.shon);
				else
					shuffle.setBackgroundResource(R.drawable.shoff);
				
			}});
		
		
		
		player.setOnErrorListener(new OnErrorListener(){

			public boolean onError(MediaPlayer arg0, int arg1, int arg2) 
			{
				if(MyD.currentSong!=null)
				{
				MyD.currentSong.isplaying=false;
				MyD.currentSong=null;
				}
				player.reset();
				MyD.isInited = false;
				
				return true;
			}});
		
		list.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long id) 
			{
				SongD song = (SongD) list.getItemAtPosition(position);
				if(!song.isplaying)
				{
					if(MyD.currentSong!=null)
						MyD.currentSong.isplaying=false;					
					MyD.currentSong=song;
					MyD.paused=false;
					stop();
					if(MusikLegal.on)
						play();
					else
					{
						//Toast.makeText(getApplicationContext(), Settings.expp, Toast.LENGTH_SHORT).show();
						final String uname = MusikLegal.mPreferences.getString("UserName", "");
						final String pass = MusikLegal.mPreferences.getString("PassWord", "");
						AlertDialog.Builder dialog = new AlertDialog.Builder(MyPlayList.this);
				    	dialog.setTitle(Settings.jmulaisubs);
				    	
				    	dialog.setMessage(Settings.warning);
				    	//dialog.setCancelable(false);
				    	dialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){

							

							public void onClick(DialogInterface arg0,
									int arg1) {
								
								String bal = MusikLegal.mPreferences.getString("Balance", "0");
								if(Integer.parseInt(bal)<1000)
								{
									AlertDialog.Builder dialog = new AlertDialog.Builder(MyPlayList.this);
							    	dialog.setTitle(Settings.jmulaisubs);
							    	
							    	dialog.setMessage(Settings.bangkrut);
							    	
							    	dialog.setPositiveButton("Input Voucher", new DialogInterface.OnClickListener(){

										

										public void onClick(DialogInterface arg0,
												int arg1) {
											
											AlertDialog.Builder alert = new AlertDialog.Builder(MyPlayList.this);

											   alert.setTitle("Topup by Hard Voucher");
											   alert.setMessage("Masukkan 16 digit kode voucher");
										 
											   final EditText input = new EditText(MyPlayList.this);
											   alert.setView(input);
											   alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
												   public void onClick(DialogInterface dialog, int whichButton) {
												     
													   	String vouch = input.getText().toString();
													   	DefaultHttpClient client = new DefaultHttpClient();
												        HttpPost httppost = new HttpPost("http://topup.musiklegal.com/webservice.php");
												        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
												        nvps.add(new BasicNameValuePair("username", MusikLegal.mPreferences.getString("UserName", "default")));
												        Calendar ci = Calendar.getInstance();
												   	 String tid =""+ci.get(Calendar.YEAR) + "-" + 
												      (ci.get(Calendar.MONTH) + 1) + "-" +
												      ci.get(Calendar.DAY_OF_MONTH) + " " +
												      ci.get(Calendar.HOUR) + ":" +
												      ci.get(Calendar.MINUTE) +  ":" +
												      ci.get(Calendar.SECOND);
												        nvps.add(new BasicNameValuePair("cid", tid));
												        nvps.add(new BasicNameValuePair("voucher", vouch));
												 
												        try {   
												      	  	UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
												            
												            httppost.setEntity(p_entity);
												            
												            HttpResponse response = client.execute(httppost);
												            HttpEntity responseEntity = response.getEntity();
												            

												            SAXParserFactory spf = SAXParserFactory.newInstance();
												            SAXParser sp = spf.newSAXParser();
												            XMLReader xr = sp.getXMLReader();
												            
												            LoginHandler myLoginHandler = new LoginHandler();
												            xr.setContentHandler(myLoginHandler);
												            xr.parse(retrieveInputStream(responseEntity));
												            ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
												           
												            
												            if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) 
												            {
												            	Toast.makeText(getApplicationContext(), "Saldo Musiklegal anda berhasil di topup", Toast.LENGTH_SHORT).show();
												            	
												            } else  
												            {
												            	Toast.makeText(getApplicationContext(), "Invalid voucher code", Toast.LENGTH_SHORT).show();
												            }
												      } catch (Exception e)
												      {
												          
												      }
												     }
												   });

												   alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
												     public void onClick(DialogInterface dialog, int whichButton) {
												      
												     }
												   });
												   alert.setIcon(R.drawable.oc2);
												   alert.show(); 
											
											
										}});
							    	dialog.setNegativeButton("SMS Subscribe", new DialogInterface.OnClickListener() {
										
										public void onClick(DialogInterface dialog, int which) {
											//dialog.dismiss();
											startActivity(new Intent(getApplicationContext(),TopUp.class));
											
										}
									});
							    	dialog.create();
							    	dialog.setIcon(R.drawable.oc2);
							        dialog.show();
								}
								else
									startSubscription(uname,pass,MyPlayList.this);
									
								
							}});
				    	dialog.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								
							}
						});
				    	dialog.create();
				    	dialog.setIcon(R.drawable.oc2);
				        dialog.show();
				        
					}
				}
			}});
		
		
		search.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v) {
				
					cari.clear();
					//hasil.clear();
					for(SongD o:MusikLegal.myPlaylist)
					{	
								if(o.title.toLowerCase().contains(srch.getText().toString().toLowerCase()) ||
										o.artist.toLowerCase().contains(srch.getText().toString().toLowerCase()))
								cari.add(o);
					}
					
					ma.list =cari;		
					
					TimerTask task = new TimerTask(){

						@Override
						public void run() {
							ma.list=hasil;
							h.post(new Runnable(){

								public void run() {
									list.invalidateViews();
									time.cancel();
									
								}});
							
						}};
						time = new Timer();
						time.schedule(task, 5000);
					
					//firstSong=true;
					//MyD.isInited=false;
					list.invalidateViews();
				
				
			}});
		
		timeBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
			
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				
				if(!close && fromUser)
				{
					player.seekTo(progress);
					if(!MusikLegal.on)
						Toast.makeText(getApplicationContext(), Settings.expp, Toast.LENGTH_SHORT).show();
				}
				
					
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				
				
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
			
				
			}});
		
		player.setOnCompletionListener(new OnCompletionListener(){

			public void onCompletion(MediaPlayer mp) {
				MyD.currentSong.isplaying=false;
				
				
					if(MyD.modeRepeat == 2)
						replay();
					else if(hasil.indexOf(MyD.currentSong)<hasil.size()-1||MyD.shuffling||MyD.modeRepeat==1)
						next(true);
					else
						{
						stop();
						play.setBackgroundResource(R.drawable.play);
						MyD.isInited=true;
						}
				
				
				
				
				list.invalidateViews();
				
			}});
		
		next.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) 
			{
				if(hasil.size()>0)
					next(true);
			}});
		
		prev.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) 
			{
					next(false);
			}});
		
		play.setOnClickListener(new OnClickListener(){

			public void onClick(View arg0) 
			{
				if(hasil.size()>0)
				play();
			}});
		list.invalidateViews();
		
		
	}
	
	void replay()
	{
		player.reset();
		if(MusikLegal.on)
		{
		
		try {
			player.setDataSource(MusikLegal.mainFolder+"/temp");
			player.prepare();
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	
	timeBar.setProgress(0);
	MyD.paused=true;
	decodeTimeElapse(0,duration);
	player.start();
	MyD.currentSong.isplaying=true;
	
	new Thread(new Runnable(){

		public void run() {
			try {
				
				if(MusikLegal.internet(getApplicationContext()))
					
					PlaylistSender.sendSong(new File(MyD.currentSong.location), getApplicationContext());
				else
					MusikLegal.log.addSong(new File(MyD.currentSong.location), getApplicationContext());
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}}).start();
	play.setBackgroundResource(R.drawable.pausebut);
	replayed=true;
		}
		else
		{
			stop();
			Toast.makeText(getApplicationContext(), Settings.expp, Toast.LENGTH_SHORT).show();
		}
	
	}
	
	void stop()
	{
	
		player.reset();
		MyD.currentSong.isplaying=false;
		MyD.isInited = false;
		timeBar.setProgress(0);
		status.setText("Select Song to play");
		list.invalidateViews();
		decodeTimeElapse(0,duration);
		play.setBackgroundResource(R.drawable.play);
		
		//timeBar.setEnabled(false);
	}
	
	void next(boolean isForward)
	{
		MyD.currentSong.isplaying=false;
		MyD.paused=false;
		MyD.isInited=false;
		player.reset();
		if(isForward)
		{
			
			if(!MyD.shuffling)
			{
				if(hasil.indexOf(MyD.currentSong)<hasil.size()-1||MyD.modeRepeat==1)
				{
					getNextSong(isForward);
					MyD.currentSong=nextSong;
						
					play();
					MyD.paused=false;
				}
				else
				{
					stop();
				}
			}
			else
			{
				if(hasil.size()>1)
				{	getNextSong(isForward);
				MyD.currentSong=nextSong;
				
					
					
					play();
					MyD.paused=false;
				}
				else
				{
					stop();
				}
			}
			
			
		}
		else
		{
			if(!MyD.shuffling)
			{
				if(hasil.indexOf(MyD.currentSong)>0||MyD.modeRepeat==1)
				{
					getNextSong(isForward);
					MyD.currentSong=nextSong;
					
						//player.reset();
						
						play();
						MyD.paused=false;
					
				}
				else
				{
					stop();
				}
			}
			else
			{
				if(hasil.size()>1)
				{	
					getNextSong(isForward);
					MyD.currentSong=nextSong;
				
					
					
					play();
					MyD.paused=false;
				}
				else
				{
					stop();
				}
			}
		}
		
	}
	
	void changeMode()
	{
		MyD.modeRepeat=(MyD.modeRepeat+1)%3;
		if(hasil.size()!=0)
		getNextSong(true);
	}
	
	void changeShuffle()
	{
		
		MyD.shuffling = !MyD.shuffling;
		if(hasil.size()>1)
		getNextSong(true);
	}
	
	public void onDestroy()
	{
		close = true;
		System.gc();
		ma.list= hasil;
		if(ma!=null)
			ma.clear();
		super.onDestroy();
	}
	
	void setEnabledAll(boolean enable)
	{
		prev.setEnabled(enable);
		play.setEnabled(enable);
		next.setEnabled(enable);
		//stop.setEnabled(enable);
//		shuffle.setEnabled(enable);
//		repeat.setEnabled(enable);
	}
	
	public void getNextSong(boolean isForward)
	{
		if(!MyD.shuffling)
		{
			if(isForward)
			{
				if(MyD.modeRepeat ==0 || MyD.modeRepeat==2)
				{
					if(hasil.indexOf(MyD.currentSong) == hasil.size()-1)
					{
						return;
					}
					else
					{
						nextSong = hasil.get((hasil.indexOf(MyD.currentSong)+1));
						return;
					}
				}
				else if(MyD.modeRepeat==1)
				{	
						nextSong = hasil.get((hasil.indexOf(MyD.currentSong)+1)%hasil.size());
						return;
				}
			}
			else
			{
				if(MyD.modeRepeat ==0 || MyD.modeRepeat==2)
				{
					if(hasil.indexOf(MyD.currentSong) <= 0)
					{
						return;
					}
					else
					{
						nextSong = hasil.get((hasil.indexOf(MyD.currentSong)-1));
						return;
					}
				}
				else if(MyD.modeRepeat==1)
				{
						
						nextSong = hasil.get((hasil.indexOf(MyD.currentSong)-1+hasil.size())%hasil.size());
						return;
				}
			}
			
		}
		else 
		{
			if(hasil.size()>1)
			nextSong=hasil.get(getRandom());
		}
	
		return;
	}
	
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		menu.add(0,MainMenu.About,0,"About");
		menu.add(0,MainMenu.Subs,0,MainMenu.subsc);
		return true;
	}
	
	int getRandom()
	{
		
		int r = rand.nextInt(hasil.size());
		if(r==hasil.indexOf(MyD.currentSong))
			return getRandom();
		else 
			return r;
		
	}
	
	void decodeTimeElapse(int elapse, int duration)
	{
		int minute = elapse/60000;
		int second = (elapse/1000)%60;
		
		StringBuffer time=new StringBuffer(((minute<10)?("0"+minute):(minute+""))+":"+((second<10)?("0"+second):(second+""))+"/");
		minute=duration/60000;
		second = (duration/1000)%60;
		time.append(((minute<10)?("0"+minute):(minute+""))+":"+((second<10)?("0"+second):(second+"")));
		timeText.setText(time.toString());
	}
	
	
	
	void play()
	{
		
		if(MusikLegal.on)
		{
		try 
		{
			if(player.isPlaying())
			{
				player.pause();
				if(!replayed)
				{
					play.setBackgroundResource(R.drawable.play);
				}
				else
					replayed=false;
				MyD.paused=true;
			}
			else
			{
				if(!MyD.paused)
				{
					//timeBar.setEnabled(true);
					
					player.reset();
					String p = decodeG3n(MyD.currentSong);
					player.setDataSource(p);
					player.prepare();
					timeBar.setMax(player.getDuration());
					timeBar.setProgress(0);
					h.post(new Runnable(){

						public void run() {
							status.setText(MyD.currentSong.title+" - "+MyD.currentSong.artist);
							
						}});
					
					MyD.currentSong.isplaying=true;
					duration = player.getDuration();
					h.post(new Runnable(){

						public void run() {
							decodeTimeElapse(0,duration);
							
						}});
					
					t= new Thread(this);
					player.start();
					t.start();
					h.post(new Runnable(){

						public void run() {
							
							play.setBackgroundResource(R.drawable.pausebut);
						}});
					
					MyD.isInited=true;
					firstSong=false;
					if(MusikLegal.on)
						{
						new Thread(new Runnable(){

							public void run() {
								try {
									if(MusikLegal.internet(getApplicationContext()))
										PlaylistSender.sendSong(new File(MyD.currentSong.location), getApplicationContext());
									else
									{
										MusikLegal.log.addSong(new File(MyD.currentSong.location), getApplicationContext());
									}
								} catch (IllegalStateException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (SAXException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (ParserConfigurationException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								
							}}).start();
						}
					h.post(new Runnable(){

						public void run() {
							// TODO Auto-generated method stub
							list.invalidateViews();
						}});
					
				}
				else if(!firstSong||MyD.paused)
				{
					player.start();
					h.post(new Runnable(){

						public void run() {
							play.setBackgroundResource(R.drawable.pausebut);
						}});
					
					t = new Thread(this);
					t.start();
					MyD.paused = false;
				}
				
			}
			
		} 
		catch (IllegalArgumentException e) 
		{
			player.reset();
			//status.setText("error");
			decodeTimeElapse(0,duration);
			e.printStackTrace();
		} 
		catch (IllegalStateException e) 
		{
			player.reset();
			//status.setText("error");
			decodeTimeElapse(0,duration);
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			player.reset();
			//status.setText("error");
			MyD.paused=false;
			decodeTimeElapse(0,duration);
			e.printStackTrace();
		} 		
		}
		else
		{
			Toast.makeText(getApplicationContext(), Settings.expp, Toast.LENGTH_SHORT).show();
		}
	}
	
	void sortList()
	{
		Collections.sort(hasil,banding);
	}
	
	public void onCreate(Bundle savedInstanceState)
	{
		if(!MusikLegal.internet(getApplicationContext()))
		{
			try {
				MusikLegal.log.send();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
//			finish();
		super.onCreate(savedInstanceState);
		if(!MusikLegal.on)
        {
        	
        	MainMenu.subsc = Settings.jmulaisubs;
        }
        else
        {
        	
        	MainMenu.subsc = Settings.jhentisubs;
        }
		init();
		MainMenu.setStatus(this);
		if(MyD.isInited)
		{
			duration = player.getDuration();
			timeBar.setMax(duration);
			status.setText(MyD.currentSong.title+" - "+MyD.currentSong.artist);
			decodeTimeElapse(player.getCurrentPosition(),duration);
			getNextSong(true);
			new Thread(this).start();
		}
		else if(hasil.size()!=0)
		{
			MyD.currentSong=hasil.get(0);
		}
		
	}
	
	String decodeG3n(SongD s) throws IOException
	{
		String pth=null;
		try
		{
			 pth= decrypt(new File(s.location)).getPath();
		}
		catch(Exception e)
		{
			removeItem(s);
		}
		
		return pth;
	}
	
	void removeFromPlayList(SongD song)
	{
		if(MyD.currentSong.equals(song))
		{
			MyD.currentSong.isplaying=false;
			stop();
		}
		hasil.remove(song);
		File f = new File(MusikLegal.playlist);
		BufferedWriter bw;
		try {
			 bw = new BufferedWriter((new FileWriter(f)));
			Iterator<SongD>it = hasil.iterator();
			while(it.hasNext())
			{
				SongD s = it.next();
				bw.write(s.toString()+"\n");
			}
			bw.flush();
			bw.close();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
	}
	
	synchronized void removeItem(SongD sd)
	{
		hasil.remove(sd);
		MusikLegal.myPlaylist.remove(sd);
		rewrite(hasil);
	}
	
	synchronized void rewrite(List<SongD>hasil)
	{
		File f = new File(MusikLegal.playlist);
		BufferedWriter bw;
		try {
			
			 bw = new BufferedWriter((new FileWriter(f)));
			Iterator<SongD>it = hasil.iterator();
			while(it.hasNext())
			{
				SongD s = it.next();
				bw.write(s.toString()+"\n");
			}
			bw.flush();
			bw.close();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
		
	}
	
	synchronized public File decrypt(File src) throws IOException
	{
		
		
		 File temp =  new File(MusikLegal.mainFolder+"temp");
		 int key = 1612;
		 BufferedInputStream is = new BufferedInputStream(new FileInputStream(src));
	     BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(temp));    

         int c;
         int clen = 0;
         byte[] cs= new byte[(int)src.length()-256];
         while((c = is.read()) >= 0)
         {
				if(clen>256)
				{
					c = (byte) ((c - 88) ^ (~((int) (key >> clen))));
					cs[clen-256]=(byte)c;
			   }
              clen++;
         }
         		os.write(cs);
         		is.close();
				os.flush();
		return temp; 
		
	}
	
	
	int k;
	public void run() {
		
		while(!close&&player.isPlaying())
		{
			
			k = player.getCurrentPosition();
			timeBar.setProgress(k);
			h.post(new Runnable(){

				public void run() {
					decodeTimeElapse(k,duration);
					play.setBackgroundResource(R.drawable.pausebut);
				}});
			//decodeTimeElapse(k,duration);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				
			}
			catch(IllegalStateException e)
			{
				
			}
			catch(Exception e)
			{
				
			}
		}
		
	}
	 private InputSource retrieveInputStream(HttpEntity httpEntity) {
	        InputSource insrc = null;
	        try {
	              insrc = new InputSource(httpEntity.getContent());
	        } catch (Exception e) {
	        }
	        return insrc;
	  } 
	
	public boolean onCreateOptionsMenu(Menu menu){

		
		menu.add(0,MainMenu.About,0,"About");
		
		menu.add(0,MainMenu.Subs,0,MainMenu.subsc);

		return true;

		}
	public boolean onOptionsItemSelected (MenuItem item){

		switch (item.getItemId()){
		
		case MainMenu.Subs:
			if(MusikLegal.internet(getApplicationContext()))
			{
			if(MainMenu.subsc.equals("Stop Subscription")||MainMenu.subsc.equals("Berhenti berlangganan"))
			{	
				AlertDialog.Builder dialog2 = new AlertDialog.Builder(this);
	        	dialog2.setTitle(MainMenu.subsc);
	        	dialog2.setMessage(Settings.hentisubs);
	        	//dialog2.setCancelable(false);
	        	dialog2.setPositiveButton(Settings.yes, new DialogInterface.OnClickListener() {
	        	public void onClick(DialogInterface dialog, int id) 
	        	{	           
	        			String username = MusikLegal.mPreferences.getString("UserName", "default");
					   String uid = MusikLegal.getUID(getApplicationContext());
				       String pass = MusikLegal.mPreferences.getString("PassWord", "default");
				       String subid = MusikLegal.mPreferences.getString("SubId", "default") ;
				    	
					   DefaultHttpClient client = new DefaultHttpClient();
				       HttpPost httppost = new HttpPost("http://secure.musiklegal.com/subscription/stop");
				       List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
				       nvps.add(new BasicNameValuePair("USERNAME", username));
				       nvps.add(new BasicNameValuePair("UID", uid));
				       nvps.add(new BasicNameValuePair("PASSWORD", pass));
				       nvps.add(new BasicNameValuePair("SUBSCRIPTION_ID", subid));

				       try {   
				    	    UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
	    	            
	    	            httppost.setEntity(p_entity);
	    	            
	    	            HttpResponse response = client.execute(httppost);
	    	            HttpEntity responseEntity = response.getEntity();
	    	            

	    	            SAXParserFactory spf = SAXParserFactory.newInstance();
	    	            SAXParser sp = spf.newSAXParser();
	    	            XMLReader xr = sp.getXMLReader();
	    	            
	    	            LoginHandler myLoginHandler = new LoginHandler();
	    	            xr.setContentHandler(myLoginHandler);
	    	            xr.parse(retrieveInputStream(responseEntity));
	    	            ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
	    	           
	    	            
				           if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) 
				           {
				              MusikLegal.mPreferences.edit().remove("START").commit();
				              MusikLegal.mPreferences.edit().remove("SubId").commit();
				              MusikLegal.mPreferences.edit().remove("SubDate").commit();
				              MusikLegal.end_subscription=null;
				              MusikLegal.mPreferences.edit().commit();
				              if(MyD.currentSong!=null&&MyD.isInited)
		 			    		 {
//		 			    		 MyD.currentSong.isplaying=false;
//		 			    		 MyD.player.reset();
//		 			    		 MyD.isInited=false;
//		 			    		 MyD.paused=false;
//		 			    		 MyD.currentSong=null;
		 			    		 stop();
		 			    		 }
				             
				              MusikLegal.on =false;
				              
				              MainMenu.setStatus(MyPlayList.this);
				              MainMenu.subsc=Settings.jmulaisubs;
				        	  Toast.makeText(getApplicationContext(), "Stop Subscription Succes", Toast.LENGTH_SHORT).show();
				           } 
				           else 
				           {
				        	  Toast.makeText(getApplicationContext(), "Error occured "+parsedLoginDataSet.getExtractedString(),  Toast.LENGTH_SHORT).show();
				                  
				           }
				           
				     } catch (Exception e)
				     {
				    	Toast.makeText(getApplicationContext(), "Error occured", Toast.LENGTH_SHORT).show();
						
				     }
	        	}
	        	});
	        	dialog2.setNegativeButton(Settings.no, new DialogInterface.OnClickListener() { 
	        		public void onClick(DialogInterface dialog, int which) {
	        			dialog.dismiss();
	        	} });
	        	dialog2.create();
	        	dialog2.setIcon(R.drawable.oc2);
	            dialog2.show(); 
		
			}
			else if ((MusikLegal.mPreferences.getString("Balance", "0").equals("0"))){
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
	        	dialog.setTitle(Settings.jbangkrut);
	        	dialog.setMessage(Settings.bangkrut);
	        	dialog.setCancelable(true);
	        	dialog.setPositiveButton("Input VOucher", new DialogInterface.OnClickListener() {
	        	public void onClick(DialogInterface dialog, int id)
	        	{
	        		startActivity(new Intent(getApplicationContext(), Voucher.class));
	        	}
	        	});
	        	dialog.setNegativeButton("SMS Subscribe", new DialogInterface.OnClickListener() { 
	        		public void onClick(DialogInterface dialog, int which) {
	        			startActivity(new Intent(getApplicationContext(), TopUp.class));
	        	} });
	        	dialog.create();
	        	dialog.setIcon(R.drawable.oc2);
	            dialog.show();
			}
			else if(MainMenu.subsc.equals("Start Subscription")||MainMenu.subsc.equals("Mulai berlangganan"))
	    	{
				AlertDialog.Builder dialog = new AlertDialog.Builder(this);
	        	dialog.setTitle(Settings.jmulaisubs);
	        	dialog.setMessage(Settings.mulaisubs+MusikLegal.mPreferences.getString("Balance", "0")+Settings.mulaisubs2);
	        	dialog.setCancelable(true);
	        	dialog.setPositiveButton(Settings.yes, new DialogInterface.OnClickListener() {
	        	public void onClick(DialogInterface dialog, int id)
	        	{
	        		String username = MusikLegal.mPreferences.getString("UserName", "default");
	    			String uid = MusikLegal.getUID(getApplicationContext());
	    		    String pass = MusikLegal.mPreferences.getString("PassWord", "default");
	    				
	    			DefaultHttpClient client = new DefaultHttpClient();
	    	        HttpPost httppost = new HttpPost("http://secure.musiklegal.com/subscription/start_weekly");
	    	        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
	    	        nvps.add(new BasicNameValuePair("USERNAME", username));
	    	        nvps.add(new BasicNameValuePair("UID", uid));
	    	        nvps.add(new BasicNameValuePair("PASSWORD", pass));
	    	 
	    	        try {   
	    	      	  	UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
	    	            
	    	            httppost.setEntity(p_entity);
	    	            
	    	            HttpResponse response = client.execute(httppost);
	    	            HttpEntity responseEntity = response.getEntity();
	    	            

	    	            SAXParserFactory spf = SAXParserFactory.newInstance();
	    	            SAXParser sp = spf.newSAXParser();
	    	            XMLReader xr = sp.getXMLReader();
	    	            
	    	            LoginHandler myLoginHandler = new LoginHandler();
	    	            xr.setContentHandler(myLoginHandler);
	    	            xr.parse(retrieveInputStream(responseEntity));
	    	            ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
	    	           
	    	           

	    	            SharedPreferences.Editor editor=MusikLegal.mPreferences.edit();
	    	            if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) 
	    	            {
	    	            	
	   	                  	editor.remove("SubDate").commit();
	   	                  	editor.remove("START").commit();
	   	                  	editor.remove("SubId").commit();
	   	                  	MainMenu.endDate = parsedLoginDataSet.getDate();
	   	                  	
	    	            	if(parsedLoginDataSet.getSiD()!=null)
	                       {
	    	            		editor.putString("SubDate", parsedLoginDataSet.getDate()).commit();
		    	            	editor.putString("START", parsedLoginDataSet.getStart()).commit();
		                       	editor.putString("SubId", parsedLoginDataSet.getSiD()).commit();
		                       	
		                       	
	                       }
	    	            	
	    	            	
	    	            	MusikLegal.on = true;
	    	            	MainMenu.subsc=Settings.jhentisubs;
	    	            	MainMenu.setStatus(MyPlayList.this);
	    	            	
	    	            	Toast.makeText(getApplicationContext(), Settings.thank, Toast.LENGTH_SHORT).show();
	    	                 
	    	            } else  
	    	            {
	    	            	Toast.makeText(getApplicationContext(), Settings.error, Toast.LENGTH_SHORT).show();
	    	            }
	    	      } catch (Exception e)
	    	      {
	    	          
	    	      }
	        	}
	        	});
	        	dialog.setNegativeButton(Settings.no, new DialogInterface.OnClickListener() { 
	        		public void onClick(DialogInterface dialog, int which) {
	        			dialog.dismiss();
	        	} });
	        	dialog.create();
	        	dialog.setIcon(R.drawable.oc2);
	            dialog.show();
			
	    	}
			else
	        {
	        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Error");
			alertDialog.setMessage(Settings.gakonek);
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
				public void onClick(DialogInterface dialog, int which) {
				finish();
				}
			});
			alertDialog.setIcon(R.drawable.oc2);
			alertDialog.show();
	        }
			
			}
		return true;


		case MainMenu.About:
			Toast.makeText(getApplicationContext(), "Version 1.3.5", Toast.LENGTH_SHORT).show();
			
			return true;
		}
		return false;
	}
	
	private void browseTo(WebView wv, String url) 
	{
		wv.getSettings().setJavaScriptEnabled(true);
		wv.getSettings().setPluginsEnabled(true);
		//wv.getSettings().setAppCacheEnabled(false);
		wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		wv.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
            	
            	
            }
        });
 
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                // Handle the error
            }
 
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
            	
            	
            	view.loadUrl(url);
            	
                return true;
            }
            
            public void onPageFinished(WebView view, String url)
            {
            	
            
            }
        });
 
		 wv.loadUrl(url);
		
	}
	
	void removeAll()
	{
		hasil.clear();
		MusikLegal.myPlaylist.clear();
		rewrite(hasil);
	}
	
	
	void startSubscription(final String uname, final String password, final Activity act)
	{
		
		//showDialog(0);
		
		//Toast.makeText(getApplicationContext(), "act", 1).show();
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    	dialog.setTitle(Settings.jmulaisubs);
    	dialog.setMessage(Settings.mulaisubs+MusikLegal.mPreferences.getString("Balance", "0")+Settings.mulaisubs2);
    	dialog.setCancelable(true);
    	dialog.setPositiveButton(Settings.yes, new DialogInterface.OnClickListener() {
    	public void onClick(DialogInterface dialog, int id)
    	{	
    		final String username =uname;
			final String uid = MusikLegal.getUID(getApplicationContext());
		    final String pass = password;
		    
		    
		    	
		    
    		
    		new Thread(new Runnable(){

				private String endDate;

				public void run() {
					// TODO Auto-generated method stub
					
						
					DefaultHttpClient client = new DefaultHttpClient();
			        HttpPost httppost = new HttpPost("http://secure.musiklegal.com/subscription/start_weekly");
			        List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
			        nvps.add(new BasicNameValuePair("USERNAME", username));
			        nvps.add(new BasicNameValuePair("UID", uid));
			        nvps.add(new BasicNameValuePair("PASSWORD", pass));
			 
			        try {   
			      	  	UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
			            
			            httppost.setEntity(p_entity);
			            
			            HttpResponse response = client.execute(httppost);
			            HttpEntity responseEntity = response.getEntity();
			            

			            SAXParserFactory spf = SAXParserFactory.newInstance();
			            SAXParser sp = spf.newSAXParser();
			            XMLReader xr = sp.getXMLReader();
			            
			            LoginHandler myLoginHandler = new LoginHandler();
			            xr.setContentHandler(myLoginHandler);
			            xr.parse(new InputSource(responseEntity.getContent()));
			            ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
			           final String tes = parsedLoginDataSet.getExtractedString();
			            //Log.d("Musik Legal: subscription",tes );

			            //removeDialog(0);
			            if (tes.compareToIgnoreCase("SUCCESS")==0) 
			            {
			            	MainMenu.subsc=Settings.jhentisubs;
			            	MusikLegal.on = true;
			            	h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.thank, Toast.LENGTH_SHORT).show();
									try {
										Settings.checkBalance();
									} catch (ClientProtocolException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (ParserConfigurationException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (SAXException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									//play();
									
					            	
								}});
			            	
			            	 SharedPreferences.Editor editor=MusikLegal.mPreferences.edit();
			                  
			            	 editor.remove("START").commit();
					              editor.remove("SubId").commit();
					              editor.remove("SubDate").commit();
					              endDate = parsedLoginDataSet.getDate();
			            	if(parsedLoginDataSet.getSiD()!=null)
		                   {
		    	            	editor.putString("SubDate", parsedLoginDataSet.getDate()).commit();
		    	            	editor.putString("START", parsedLoginDataSet.getStart()).commit();
		                       	editor.putString("SubId", parsedLoginDataSet.getSiD()).commit();
		                   }
			            	
			            	
			            	
			            	
			            	
			            	h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									MainMenu.setStatus(act);
								}});
			            	
			                 
			            }
			            else if(tes.equalsIgnoreCase("INSUFFICIENT BALANCE"))
			            {
			            	h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.jbangkrut, Toast.LENGTH_SHORT).show();
								}});
			            }
			            else  
			            {
			            	h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(), Settings.error, Toast.LENGTH_SHORT).show();
								}});
			            	
			            }
			      } catch (Exception e)
			      {
			          
			      }
				
				}}).start();
    		
    	}

    	});
    	
    	dialog.setNegativeButton(Settings.no, new DialogInterface.OnClickListener() { 
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    	} });
    	dialog.create();
    	dialog.setIcon(R.drawable.oc2);
        dialog.show();
    	
    	}
	
	ProgressDialog dialog1;
	protected Dialog onCreateDialog(int id) {
        switch (id) {
              case 0: {
                    dialog1 = new ProgressDialog(this);
                    dialog1.setMessage("Processing...");
                    dialog1.setIndeterminate(true);
                    dialog1.setCancelable(true);
                    return dialog1;                   
              }
        }
        return null;
  }
	
	
}
